/*
 * Copyright (C) 2014 BlueKitchen GmbH
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holders nor the names of
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 * 4. Any redistribution, use, or modification is done solely for
 *    personal benefit and not for any commercial purpose or for
 *    monetary gain.
 *
 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Please inquire about commercial licensing options at
 * contact@bluekitchen-gmbh.com
 *
 */

#define BTSTACK_FILE__ "gatt_browser.c"

// *****************************************************************************
/* EXAMPLE_START(gatt_browser): GATT Client - Discover Primary Services
 *
 * @text This example shows how to use the GATT Client
 * API to discover primary services and their characteristics of the first found
 * device that is advertising its services.
 *
 * The logic is divided between the HCI and GATT client packet handlers.
 * The HCI packet handler is responsible for finding a remote device,
 * connecting to it, and for starting the first GATT client query.
 * Then, the GATT client packet handler receives all primary services and
 * requests the characteristics of the last one to keep the example short.
 *
 */
// *****************************************************************************

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "btstack.h"

// gatt_browser.gatt contains the declaration of the provided GATT Services + Characteristics
// gatt_browser.h    contains the binary representation of gatt_browser.gatt
// it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py gatt_browser.gatt gatt_browser.h
// it needs to be regenerated when the GATT Database declared in gatt_browser.gatt file is modified
#include "gatt_browser.h"

typedef struct _advertising_report_t {
    uint8_t type;
    uint8_t event_type;
    uint8_t address_type;
    bd_addr_t address;
    uint8_t rssi;
    uint8_t length;
    const uint8_t *data;
} advertising_report_t;

typedef struct _characteristic_value_t {
    uint16_t size;
    uint8_t *value;
    gatt_client_characteristic_t characteristic;
    gatt_client_characteristic_descriptor_t descriptor;
} characteristic_value_t;

typedef characteristic_value_t descriptor_value_t;

// Connections vars
static bd_addr_t target_addr;
static int target_addr_found = 0;
static uint8_t target_addr_type = 0;
static hci_con_handle_t connection_handler;

// Services vars
static gatt_client_service_t services[128] = {0};
static gatt_client_characteristic_t characteristics[128] = {0};
static gatt_client_characteristic_descriptor_t descriptors[128] = {0};
static characteristic_value_t characteristics_value[128] = {0};
static descriptor_value_t descriptors_value[128] = {0};
static uint16_t characteristics_values_handles[128] = {0};
static int service_count = 0;
static int service_index = 0;
static int characteristic_count = 0;
static int characteristic_index = 0;
static int descriptor_count = 0;
static int descriptor_index = 0;
static int characteristic_value_count = 0;
static int characteristic_value_index = 0;

// State vars
static int search_pri_services = 0;
static int search_sec_services = 0;
static int search_inc_services = 0;
static int pairing_start = 0;
static int search_characteristics = 0;
static int search_descriptors = 0;
static int read_all_characteristics_value = 0;
static int read_all_descriptors_value = 0;
static int write_all_characteristics_value = 0;
static int write_all_descriptors_value = 0;

// Callback handlers
static btstack_packet_callback_registration_t hci_event_callback_registration;
static btstack_packet_callback_registration_t sm_event_callback_registration;

/* @section GATT client setup
 *
 * @text In the setup phase, a GATT client must register the HCI and GATT client
 * packet handlers, as shown in Listing GATTClientSetup.
 * Additionally, the security manager can be setup, if signed writes, or
 * encrypted, or authenticated connection are required, to access the
 * characteristics, as explained in Section on [SMP](../protocols/#sec:smpProtocols).
 */

/* LISTING_START(GATTClientSetup): Setting up GATT client */

// Handles connect, disconnect, and advertising report events,
// starts the GATT client, and sends the first query.
static void handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);

// Handles GATT client query results, sends queries and the
// GAP disconnect command when the querying is done.
static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);

static void le_device_delete_all(void)
{
    uint16_t index;
    uint16_t max_count = le_device_db_max_count();

    for (index = 0; index < max_count; index++) {
        int addr_type;
        bd_addr_t addr;
        memset(addr, 0, 6);
        le_device_db_info(index, &addr_type, addr, NULL);
        if (addr_type != BD_ADDR_TYPE_UNKNOWN) {
            log_info("Remove LE Device with index %u, addr type %x, addr %s", index, addr_type, bd_addr_to_str(addr));
            le_device_db_remove(index);
        }
    }
    le_device_db_dump();
}

static void gatt_client_setup(void)
{

    // Initialize L2CAP and register HCI event handler
    l2cap_init();

    // Optionally, Setup security manager
    sm_init();
    sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
    sm_set_authentication_requirements(SM_AUTHREQ_BONDING);
    sm_set_encryption_key_size_range(7, 16);
    sm_set_request_security(false);
    sm_set_ignore_security_request(true);

    // setup le device db
    le_device_db_init();

    // Initialize GATT client
    gatt_client_init();

    // register for HCI events
    hci_event_callback_registration.callback = &handle_hci_event;
    hci_add_event_handler(&hci_event_callback_registration);

    // register for SM events
    sm_event_callback_registration.callback = &handle_hci_event;
    sm_add_event_handler(&sm_event_callback_registration);
}
/* LISTING_END */

static void printUUID(uint8_t *uuid128, uint16_t uuid16)
{
    if (uuid16) {
        printf("%04x", uuid16);
    }
    else {
        printf("%s", uuid128_to_str(uuid128));
    }
}

static void dump_advertising_report(advertising_report_t *e)
{
    printf("    * adv. event: evt-type %u, addr-type %u, addr %s, rssi %u, length adv %u, data: ", e->event_type,
           e->address_type, bd_addr_to_str(e->address), e->rssi, e->length);
    printf_hexdump(e->data, e->length);
}

static void dump_service(gatt_client_service_t *service)
{
    printf("    * service: [0x%04x-0x%04x], uuid ", service->start_group_handle, service->end_group_handle);
    printUUID(service->uuid128, service->uuid16);
    printf("\n");
}

static void dump_characteristic(gatt_client_characteristic_t *characteristic)
{
    printf("    * characteristic: [0x%04x-0x%04x-0x%04x], properties 0x%02x, uuid ",
           characteristic->start_handle, characteristic->value_handle, characteristic->end_handle, characteristic->properties);
    printUUID(characteristic->uuid128, characteristic->uuid16);
    printf("\n");
}

static void dump_descriptor(gatt_client_characteristic_descriptor_t *descriptor)
{
    printf("    * descriptor: [0x%04x], uuid ",
           descriptor->handle);
    printUUID(descriptor->uuid128, descriptor->uuid16);
    printf("\n");
}

static void fill_advertising_report_from_packet(advertising_report_t *report, uint8_t *packet)
{
    gap_event_advertising_report_get_address(packet, report->address);
    report->event_type = gap_event_advertising_report_get_advertising_event_type(packet);
    report->address_type = gap_event_advertising_report_get_address_type(packet);
    report->rssi = gap_event_advertising_report_get_rssi(packet);
    report->length = gap_event_advertising_report_get_data_length(packet);
    report->data = gap_event_advertising_report_get_data(packet);
}

static int gatt_discover_all_characteristics()
{
    gatt_client_service_t service;
    if (service_index < service_count) {
        printf("GATT browser - CHARACTERISTIC for SERVICE %s, [0x%04x-0x%04x]\n",
               uuid128_to_str(service.uuid128), service.start_group_handle, service.end_group_handle);
        service = services[service_index++];
        gatt_client_discover_characteristics_for_service(handle_gatt_client_event, connection_handler, &service);
        return 1;
    }

    return 0;
}

static int gatt_discover_all_descriptors()
{
    gatt_client_characteristic_t characteristic;
    if (characteristic_index < characteristic_count) {
        printf("GATT browser - DESCRIPTOR for CHARACTERISTIC %s, [0x%04x-0x%04x]\n",
               uuid128_to_str(characteristic.uuid128), characteristic.start_handle, characteristic.end_handle);
        characteristic = characteristics[characteristic_index++];
        gatt_client_discover_characteristic_descriptors(handle_gatt_client_event, connection_handler, &characteristic);
        return 1;
    }

    return 0;
}

static int gatt_read_all_characteristics_value()
{
    gatt_client_characteristic_t characteristic;
    if (characteristic_index < characteristic_count) {
        characteristic = characteristics[characteristic_index++];
        gatt_client_read_value_of_characteristic(handle_gatt_client_event, connection_handler, &characteristic);
        return 1;
    }

    return 0;
}

static int gatt_read_all_descriptors_value()
{
    gatt_client_characteristic_descriptor_t descriptor;
    if (descriptor_index < descriptor_count) {
        descriptor = descriptors[descriptor_index++];
        gatt_client_read_characteristic_descriptor(handle_gatt_client_event, connection_handler, &descriptor);
        return 1;
    }

    return 0;
}

static int gatt_write_all_characteristics_value()
{
    gatt_client_characteristic_t characteristic;
    characteristic_value_t characteristic_value;
    if (characteristic_index < characteristic_count) {
        characteristic = characteristics[characteristic_index];
        characteristic_value = characteristics_value[characteristic_index++];
        if (characteristic_value.value != NULL)
            gatt_client_write_value_of_characteristic(handle_gatt_client_event,
                                                      connection_handler,
                                                      characteristic.value_handle,
                                                      characteristic_value.size,
                                                      characteristic_value.value);
        else
            gatt_client_write_value_of_characteristic(handle_gatt_client_event,
                                                      connection_handler,
                                                      characteristic.value_handle,
                                                      1,
                                                      (uint8_t *)"\0");

        return 1;
    }

    return 0;
}

static int gatt_write_all_descriptors_value()
{
    gatt_client_characteristic_descriptor_t descriptor;
    descriptor_value_t descriptor_value;
    if (descriptor_index < descriptor_count) {
        descriptor = descriptors[descriptor_index];
        descriptor_value = descriptors_value[descriptor_index++];
        if (descriptor_value.value != NULL)
            gatt_client_write_characteristic_descriptor(handle_gatt_client_event,
                                                        connection_handler,
                                                        &descriptor,
                                                        descriptor_value.size,
                                                        descriptor_value.value);
        else
            gatt_client_write_characteristic_descriptor(handle_gatt_client_event,
                                                        connection_handler,
                                                        &descriptor,
                                                        1,
                                                        (uint8_t *)"\0");

        return 1;
    }

    return 0;
}

static void reset_vars()
{
    search_pri_services = 0;
    search_sec_services = 0;
    search_inc_services = 0;
    pairing_start = 0;
    search_characteristics = 0;
    search_descriptors = 0;
    read_all_characteristics_value = 0;
    read_all_descriptors_value = 0;
    write_all_characteristics_value = 0;
    write_all_descriptors_value = 0;
    service_count = 0;
    service_index = 0;
    characteristic_count = 0;
    characteristic_index = 0;
    descriptor_count = 0;
    descriptor_index = 0;
    characteristic_value_count = 0;
    characteristic_value_index = 0;
}

/* @section HCI packet handler
 *
 * @text The HCI packet handler has to start the scanning,
 * to find the first advertising device, to stop scanning, to connect
 * to and later to disconnect from it, to start the GATT client upon
 * the connection is completed, and to send the first query - in this
 * case the gatt_client_discover_primary_services() is called, see
 * Listing GATTBrowserHCIPacketHandler.
 */

/* LISTING_START(GATTBrowserHCIPacketHandler): Connecting and disconnecting from the GATT client */
static void handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
{
    UNUSED(channel);
    UNUSED(size);

    if (packet_type != HCI_EVENT_PACKET)
        return;
    advertising_report_t report;

    uint8_t event = hci_event_packet_get_type(packet);
    bd_addr_t event_address;

    switch (event) {
    case BTSTACK_EVENT_STATE:
        // BTstack activated, get started
        if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING)
            break;

        // Delete all link keys
        le_device_delete_all();

        if (target_addr_found) {
            printf("Trying to connect to %s\n", bd_addr_to_str(target_addr));
            gap_auto_connection_start(target_addr_type, target_addr);
            break;
        }

        printf("Start scanning!\n");
        gap_set_scan_parameters(0, 0x0030, 0x0030);
        gap_start_scan();
        break;
    case GAP_EVENT_ADVERTISING_REPORT:
        fill_advertising_report_from_packet(&report, packet);
        dump_advertising_report(&report);

        // stop scanning, and connect to the device
        gap_stop_scan();
        gap_connect(report.address, report.address_type);
        break;
    case HCI_EVENT_LE_META:
        // wait for connection complete
        if (hci_event_le_meta_get_subevent_code(packet) != HCI_SUBEVENT_LE_CONNECTION_COMPLETE)
            break;
        connection_handler = hci_subevent_le_connection_complete_get_connection_handle(packet);
        reset_vars();
        // query primary services
        search_pri_services = 1;
        gatt_client_discover_primary_services(handle_gatt_client_event, connection_handler);
        break;
    case HCI_EVENT_DISCONNECTION_COMPLETE:
        printf("\nGATT browser - DISCONNECTED\n");
        if (target_addr_found) {
            // printf("Trying to connect to %s\n", bd_addr_to_str(target_addr));
            reset_vars();
            // gap_connect(target_addr, 0);
            // gap_auto_connection_start(0, target_addr);
            break;
        }
        break;

    case SM_EVENT_PASSKEY_INPUT_NUMBER:
        // store peer address for input
        printf("\nGAP Bonding: Using 6 digit passkey: '000000'");
        sm_passkey_input(connection_handler, 000000);
        break;

    case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
        printf("\nGAP Bonding: Display Passkey '%06u\n", little_endian_read_32(packet, 11));
        break;

    case SM_EVENT_PASSKEY_DISPLAY_CANCEL:
        printf("\nGAP Bonding: Display cancel\n");
        break;

    case SM_EVENT_JUST_WORKS_REQUEST:
        // auto-authorize connection if requested
        sm_just_works_confirm(little_endian_read_16(packet, 2));
        printf("Just Works request confirmed\n");
        break;

    case SM_EVENT_IDENTITY_CREATED:
        puts("Pairing Successful");
        // Start characterists discovery
        search_characteristics = 1;
        service_index = 0;
        gatt_discover_all_characteristics();
        break;

    case SM_EVENT_AUTHORIZATION_REQUEST:
        // auto-authorize connection if requested
        sm_authorization_grant(little_endian_read_16(packet, 2));
        break;

    case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
        puts("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED not handled");
        // search_characteristics = 1;
        // service_index = 0;
        // gatt_discover_all_characteristics();
        // reverse_bd_addr(&packet[5], event_address);
        // // skip already detected pts
        // if (memcmp(event_address, target_addr, 6) == 0)
        //     break;
        // memcpy(target_addr, event_address, 6);
        // current_pts_address_type = packet[4];
        // le_device_db_index = little_endian_read_16(packet, 11);
        // printf("Address resolving succeeded: resolvable address %s, addr type %u\n",
        //        bd_addr_to_str(target_addr), current_pts_address_type);
        break;

    case SM_EVENT_IDENTITY_RESOLVING_STARTED:
        puts("SM_EVENT_IDENTITY_RESOLVING_STARTED");
        break;

    case SM_EVENT_IDENTITY_RESOLVING_FAILED:
        puts("SM_EVENT_IDENTITY_RESOLVING_FAILED");
        // puts("Pairing Successful");
        // // Start characterists discovery
        // search_characteristics = 1;
        // service_index = 0;
        // gatt_discover_all_characteristics();
        break;

    case HCI_EVENT_ENCRYPTION_CHANGE:
        puts("Encryption Started");
        // Start characterists discovery
        search_characteristics = 1;
        service_index = 0;
        gatt_discover_all_characteristics();
        break;

    default:
        break;
    }
}
/* LISTING_END */

/* @section GATT Client event handler
 *
 * @text Query results and further queries are handled by the GATT client packet
 * handler, as shown in Listing GATTBrowserQueryHandler. Here, upon
 * receiving the primary services, the
 * gatt_client_discover_characteristics_for_service() query for the last
 * received service is sent. After receiving the characteristics for the service,
 * gap_disconnect is called to terminate the connection. Upon
 * disconnect, the HCI packet handler receives the disconnect complete event.
 */

/* LISTING_START(GATTBrowserQueryHandler): Handling of the GATT client queries */

static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
{
    UNUSED(packet_type);
    UNUSED(channel);
    UNUSED(size);

    gatt_client_service_t service;
    gatt_client_characteristic_t characteristic;
    gatt_client_characteristic_descriptor_t descriptor;
    characteristic_value_t characteristic_value;
    descriptor_value_t descriptor_value;

    switch (hci_event_packet_get_type(packet)) {
    case GATT_EVENT_SERVICE_QUERY_RESULT:
        gatt_event_service_query_result_get_service(packet, &service);
        dump_service(&service);
        services[service_count++] = service;
        break;

    case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT:
        gatt_event_included_service_query_result_get_service(packet, &service);
        dump_service(&service);
        services[service_count++] = service;
        break;

    case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
        gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
        dump_characteristic(&characteristic);
        characteristics[characteristic_count++] = characteristic;
        break;

    case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
        gatt_event_all_characteristic_descriptors_query_result_get_characteristic_descriptor(packet, &descriptor);
        dump_descriptor(&descriptor);
        descriptors[descriptor_count++] = descriptor;
        break;

    case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
        characteristic_value.size = gatt_event_characteristic_value_query_result_get_value_length(packet);
        characteristic_value.value = malloc(characteristic_value.size);
        characteristic_value.characteristic = characteristics[characteristic_index - 1];
        memcpy(characteristic_value.value,
               gatt_event_characteristic_value_query_result_get_value(packet),
               characteristic_value.size);
        printf("Characteristic %d value (hex): ", characteristic_index);
        printf_hexdump(characteristic_value.value, characteristic_value.size);
        // printf("string: %s\n", characteristic_value.value);
        characteristics_value[characteristic_index - 1] = characteristic_value;
        characteristics_values_handles[characteristic_value_count++] = characteristic_value.characteristic.value_handle;
        break;

    case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
        descriptor_value.size = gatt_event_characteristic_descriptor_query_result_get_descriptor_length(packet);
        descriptor_value.value = malloc(descriptor_value.size);
        descriptor_value.descriptor = descriptors[descriptor_index - 1];
        memcpy(descriptor_value.value,
               gatt_event_characteristic_descriptor_query_result_get_descriptor(packet),
               descriptor_value.size);
        printf("Descriptor %d value (hex): ", descriptor_index);
        printf_hexdump(descriptor_value.value, descriptor_value.size);
        // printf("string: %s\n", descriptor_value.value);
        descriptors_value[descriptor_index - 1] = descriptor_value;
        break;

    case GATT_EVENT_QUERY_COMPLETE:
        if (search_pri_services) {
            // Primary services complete
            puts("Primary Services Complete");
            service_index = 0;
            search_pri_services = 0;
            search_sec_services = 1;
            gatt_client_discover_secondary_services(handle_gatt_client_event, connection_handler);
        }
        else if (search_sec_services) {
            puts("Secondary Services Complete");
            // Secondary services complete
            search_sec_services = 0;
            search_inc_services = 1;
            gatt_client_find_included_services_for_service(handle_gatt_client_event, connection_handler, &services[service_index]);
        }
        else if (search_inc_services) {
            puts("Included Services Complete");
            // Included services complete
            search_inc_services = 0;
            pairing_start = 1;
            gatt_client_service_t aService;
            aService.start_group_handle = 0x0001;
            aService.end_group_handle = 0xffff;
            gatt_client_find_included_services_for_service(handle_gatt_client_event, connection_handler, &aService);
        }
        else if (pairing_start) {
            puts("Starting pairing");
            // Manually start pairing
            pairing_start = 0;
            sm_request_pairing(connection_handler);
        }
        else if (search_characteristics) {
            // GATT_EVENT_QUERY_COMPLETE
            if (!gatt_discover_all_characteristics()) {
                puts("Characteristics Discovery Complete");
                search_characteristics = 0;
                search_descriptors = 1;
                characteristic_index = 0;
                gatt_discover_all_descriptors();
            }
        }
        else if (search_descriptors) {
            // GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT
            if (!gatt_discover_all_descriptors()) {
                puts("Descriptors Discovery Complete");
                search_descriptors = 0;
                read_all_characteristics_value = 1;
                characteristic_index = 0;
                gatt_read_all_characteristics_value();
            }
        }
        // READ operations
        else if (read_all_characteristics_value) {
            if (!gatt_read_all_characteristics_value()) {
                puts("All Characteristics Read");
                read_all_characteristics_value = 0;
                read_all_descriptors_value = 1;
                descriptor_index = 0;
                gatt_read_all_descriptors_value();
            }
        }
        else if (read_all_descriptors_value) {
            if (!gatt_read_all_descriptors_value()) {
                puts("All Descriptors Read");
                read_all_descriptors_value = 0;
                write_all_characteristics_value = 1;
                characteristic_index = 0;
                gatt_write_all_characteristics_value();
            }
        }
        // WRITE Operations
        else if (write_all_characteristics_value) {
            if (!gatt_write_all_characteristics_value()) {
                puts("All Characteristics Written");
                write_all_characteristics_value = 0;
                write_all_descriptors_value = 1;
                descriptor_index = 0;
                gatt_write_all_descriptors_value();
            }
        }
        else if (write_all_descriptors_value) {
            if (!gatt_write_all_descriptors_value()) {
                puts("All Descriptors Written");
                write_all_descriptors_value = 0;
                puts("Disconnecting from target");
                gap_disconnect(connection_handler);
            }
        }

        break;
    default:
        break;
    }
}
/* LISTING_END */

#ifdef HAVE_BTSTACK_STDIN
static void usage(const char *name)
{
    fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
}
#endif

int btstack_main(int argc, const char *argv[]);
int btstack_main(int argc, const char *argv[])
{

#ifdef HAVE_BTSTACK_STDIN
    int arg = 1;
    target_addr_found = 0;

    while (arg < argc) {
        if (!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")) {
            arg++;
            target_addr_found = sscanf_bd_addr(argv[arg], target_addr);
        }
        else if (!strcmp(argv[arg], "-h") || !strcmp(argv[arg], "--help")) {
            arg++;
            usage("gatt_browser");
            exit(0);
        }
        arg++;
    }
#else
    (void)argc;
    (void)argv;
#endif

    // setup GATT client
    gatt_client_setup();

    // setup ATT server - only needed if LE Peripheral does ATT queries on its own, e.g. Android and iOS
    att_server_init(profile_data, NULL, NULL);

    // turn on!
    hci_power_control(HCI_POWER_ON);

    return 0;
}

/* EXAMPLE_END */
